// 控制器层 实现路由的处理逻辑
package controllers

import (
	"errors"
	"log"
	"operator/config"
	logs "operator/utils/logs"

	"github.com/gin-gonic/gin"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

// 定义全局的数据结构
type BasicInfo struct {
	// get请求发送的是params，需要通过form来绑定get请求字段
	ClusterId  string      `json:"clusterId"  form:"clusterId"`
	Namespace  string      `json:"namespace" form:"namespace"`
	Name       string      `json:"name" form:"name"`
	Item       interface{} `json:"item"`
	DeleteList []string    `json:"deleteList"`
	// 日志
	Container      string `json:"container" form:"container"`
	TailLines      int64  `json:"tailLines" form:"tailLines"`
	DefaultCommand string `json:"defaultCommand" form:"defaultCommand"`
}

func BasicInit(r *gin.Context, item interface{}) (clientset *kubernetes.Clientset, basicInfo BasicInfo, err error) {
	basicInfo = BasicInfo{}
	basicInfo.Item = item

	// 首先获取请求的类型
	// POST方法绑定JSON，那GET请求怎么处理这种？ requestMethod := r.Request.Method  ShouldBindQuery
	requestMethod := r.Request.Method
	if requestMethod == "GET" {
		err = r.ShouldBindQuery(&basicInfo)
		if err != nil {
			log.Printf("GET 请求绑定错误：%v", err)
		}
	} else if requestMethod == "POST" {
		err = r.ShouldBind(&basicInfo)
		if err != nil {
			log.Printf("POST 请求绑定错误：%v", err)
		}
	} else {
		err = errors.New("不支持的请求类型")
	}

	logs.Info(map[string]interface{}{"basicInfo": basicInfo}, "数据绑定结果")

	if err != nil {
		msg := "请求出错：" + err.Error()
		return nil, basicInfo, errors.New(msg)
	}

	if basicInfo.Namespace == "" {
		basicInfo.Namespace = "default"
	}

	// 获取kubeconfig
	kubeconfig := config.ClusterKubeconfig[basicInfo.ClusterId]
	restConfig, err := clientcmd.RESTConfigFromKubeConfig([]byte(kubeconfig))
	if err != nil {
		msg := "解析kubeconfig错误：" + err.Error()
		return nil, basicInfo, errors.New(msg)
	}
	// 创建一个clientset
	clientset, err = kubernetes.NewForConfig(restConfig)
	if err != nil {
		msg := "创建clientset：" + err.Error()
		return nil, basicInfo, errors.New(msg)
	}
	return clientset, basicInfo, nil
}

// create delete get list update --> 接口
// kubeutils
